package concurrecy;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

abstract class IntGenerator {
    public abstract int next();
    private volatile boolean canceled = false;
    boolean isCancel() {
        return canceled;
    }
    void cancel() {
        this.canceled = true;
    }
}

class EvenChecker implements Runnable {

    private IntGenerator intGenerator;

    public EvenChecker(IntGenerator intGenerator) {
        this.intGenerator = intGenerator;
    }

    @Override
    public void run() {
        while(!intGenerator.isCancel()) {
            int next = intGenerator.next();
            if((next & 0b1) != 0) {
                System.out.println(next + " 不是偶数");
                intGenerator.cancel();
            }
            if(next > 500000) {
                intGenerator.cancel();
                System.out.println("正常结束");
            }
        }
    }
}

class EvenIntGenerator extends IntGenerator {
    private int count = 0;
    private Lock lock = new ReentrantLock();
    @Override
    public int next() {
        lock.lock();
        try {
            count++;
            count++;
            return count;
        } finally {
            lock.unlock();
        }
    }
}

/**
 * 偶数生成器（多线程并发数据一致性问题）
 */
public class EvenGeneratorDemo {
    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        IntGenerator generator = new EvenIntGenerator();
        for (int i = 0; i < 10; i++) {
            service.execute(new EvenChecker(generator));
        }
        service.shutdown();
    }
}
